package com.mango.ch09;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class GroomFriendMapper extends Mapper<LongWritable, Text, LongWritable, MyTuple> {

	@Override
	protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, LongWritable, MyTuple>.Context context)
			throws IOException, InterruptedException {
		// TODO Auto-generated method stub

		String[] tokens = value.toString().split(" ");
		Integer userKey = Integer.valueOf(tokens[0]);
		List<Long> friends = iterableToList(tokens[1].split(","));
		// 发出所有好友关系
		for (Long fid : friends) {
			// -1表示是直接好友
			System.out.print(userKey + "的直接好友列表是" + fid + " ,");
			MyTuple firectFriend = new MyTuple(fid, -1);
			context.write(new LongWritable(userKey), firectFriend);
		}
		System.out.println("--------------------------");
		// 发出所有可能的好友关系(即设置相互好友，列出所有情况，如F,a b  则context写出 a,(b,F) 和b,(a,F)的所有情况
		// 它们有共同的好友person作为键
		for (int i = 0; i < friends.size(); i++) {
			for (int j = i + 1; j < friends.size(); j++) {
				// 可能好友1
				MyTuple possibleFriend1 = new MyTuple(friends.get(j), userKey);
				context.write(new LongWritable(friends.get(i)), possibleFriend1);
				// 可能好友 2
				MyTuple possibleFriend2 = new MyTuple(friends.get(i), userKey);
				// get(i)或者get(j)表示当前person 而MyTuple(friends.get(j),
				// userKey);表示（推荐的好友，当前person与推荐人之间的共同好友）
				context.write(new LongWritable(friends.get(j)), possibleFriend2);
				System.out.print(
						"所有可能的好友关系" + friends.get(i) + "  " + possibleFriend1.get_1() + " :" + possibleFriend1.get_2());
				System.out.print("&");
				System.out.print(
						"所有可能的好友关系" + friends.get(j) + "  " + possibleFriend2.get_1() + " :" + possibleFriend2.get_2());
			}
			System.out.println("-----------------------------");

		}

	}

	protected static List<Long> iterableToList(String[] strings) {
		// TODO Auto-generated method stub
		List<Long> list = new ArrayList<>();
		for (String it : strings) {
			list.add(Long.valueOf(it));
		}
		System.out.println("查看原始数据转换为list之后的值是："+list.toString());
		return list;
	}
}
